package com.darwin.darwinUtils
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;

	/**
	 * 
	 * @author vanCopper
	 * 
	 */	
	public class BitmapDataTool
	{
		public function BitmapDataTool()
		{
		}
		
		/**
		 *	获取一个显示对象的位图 
		 * @param displayObject
		 * @param containFiltersBounds 是否要包含滤镜所覆盖的区域
		 * @return 
		 * 
		 */
		public static function getBitmapData(displayObject:DisplayObject,containFiltersBounds:Boolean = false):BitmapData
		{
			if(displayObject == null){return null;}
			var rect:Rectangle =  displayObject.getBounds(displayObject);
			var matrix:Matrix = new Matrix(1,0,0,1,-rect.left,-rect.top);
			var colorBounds:Rectangle;
			var testBitmapData:BitmapData;
			if(containFiltersBounds)
			{
				testBitmapData = new BitmapData(displayObject.width > 0 ? displayObject.width*2 : 1,displayObject.height > 0 ? displayObject.height*2 : 1,true,0x00000000);
				var tm:Matrix = new Matrix(1,0,0,1,-rect.left + testBitmapData.width/4,-rect.top + testBitmapData.height/4);
				testBitmapData.draw(displayObject,tm);
				colorBounds = testBitmapData.getColorBoundsRect(0xFF000000,0x00000000, false);
			}
			var returnBitmapData:BitmapData;
			if(containFiltersBounds && colorBounds.width > 0 && colorBounds.height > 0)
			{
				returnBitmapData = new BitmapData(colorBounds.width,colorBounds.height,true,0x00000000); 
				returnBitmapData.copyPixels(testBitmapData,colorBounds,new Point());
				testBitmapData.dispose();
				testBitmapData = null;
			}else{
//				returnBitmapData = new BitmapData(rect.width,rect.height,true,0x64FF0000); 
				returnBitmapData = new BitmapData(rect.width,rect.height,true,0); 
				returnBitmapData.draw(displayObject,matrix);
			}
			return returnBitmapData;
		}
		
		/**
		 * 讲位图数据转换为 bitmap 
		 * @param bytesArray
		 * @param callBack
		 * 
		 */		
		public static function getBitmapByBytes(bytesArray:ByteArray,callBack:Function,key:Object=null):void
		{
			var loader:Loader=new Loader();    
			loader.loadBytes(bytesArray);//读取ByteArray    
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, bytesComplete); 
			
			function bytesComplete(e:Event):void
			{
				var targetLoader:Loader = e.target.loader;// as Loader;
				var bitmap:Bitmap = Bitmap(e.target.content);//读取Bitmap 
				if(callBack != null && key == null)
				{
					callBack(bitmap);
				}else if(callBack != null && key!=null)
				{
					callBack(bitmap,key);
				}
			}
		}
	}
}